package com.wy.ssm01.aspect;


import com.wy.ssm01.entity.MyTestEntity;
import com.wy.ssm01.entity.MyTestLog;
import com.wy.ssm01.service.TestLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private TestLogService testLogService;

    private void createLogs(MyTestEntity testEntity, String methodName, Object returnValue) {
        String message = methodName + "方法已执行,目标用户:" + testEntity + ",返回值:" + returnValue;
        MyTestLog myTestLog = new MyTestLog(null, message, new Date(), testEntity.getId());
        System.out.println(testLogService.insert(myTestLog));
    }

    private void createLogs(Integer testId, String methodName, Object returnValue) {
        String message = methodName + "方法已执行,目标用户:" + testId + ",返回值:" + returnValue;
        MyTestLog myTestLog = new MyTestLog(null, message, new Date(), testId);
        System.out.println(testLogService.insert(myTestLog));
    }

    @Around(value = "execution(* com.wy.ssm01.mapper.TestMapper.insert(..))&&args(testEntity)")
    public Object insert(ProceedingJoinPoint pjp, MyTestEntity testEntity) throws Throwable {

        Object proceed = pjp.proceed();
        createLogs(testEntity, pjp.getSignature().getName(), proceed);
        return proceed;
    }
    @Around(value = "execution(* com.wy.ssm01.mapper.TestMapper.update(..))&&args(testEntity)")
    public Object update(ProceedingJoinPoint pjp, MyTestEntity testEntity) throws Throwable {

        Object proceed = pjp.proceed();
        createLogs(testEntity, pjp.getSignature().getName(), proceed);
        return proceed;
    }

    @Around(value = "execution(* com.wy.ssm01.mapper.TestMapper.delete(..))&&args(testId)")
    public Object update(ProceedingJoinPoint pjp, Integer testId) throws Throwable {

        Object proceed = pjp.proceed();
        createLogs(testId, pjp.getSignature().getName(), proceed);
        return proceed;
    }


    @AfterReturning(pointcut = "execution(* com.wy.ssm01.mapper.TestMapper.queryById(..))&&args(id)",returning = "testEntity", argNames = "id,testEntity")
    public void testAfterReturning(Integer id,Object testEntity) throws Throwable {
        System.out.println("====================================");
        System.out.println(testEntity);
        System.out.println("====================================");
    }

}
